package com.example.springbootdemo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 84246
 */ //@Configuration
public class FilterConfig implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(FilterConfig.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUrl = request.getRequestURI();
        if (requestUrl.contains("/login")) {
            // 访问的是登录界面，请求继续向下传递
            filterChain.doFilter(request, response);
        } else {
            // 在请求前进行处理
            LOGGER.info("Before the request");
            String authorize = request.getHeader("Authentication");
            String username = request.getHeader("username");
            String usernameFromToken = JwtConfig.getUsernameFromToken(authorize);

            // 检查是否需要拦截处理
            // 这里可以根据具体需求进行逻判断，例如验证用户权限、跨域处理等。
            if (!JwtConfig.validateToken(authorize)||!usernameFromToken.equals(username)) {
                // 拦截请求，可以返回自定义的错误信息或者进行其他特殊处理
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.getWriter().println("AUTHORIZE ERROR");
                return;
            }

            // 请求继续向下传递
            filterChain.doFilter(request, response);

            // 在请求后进行处理
            LOGGER.info("After the request");

        }
    }

    @Override
    public void destroy() {

    }

}
